package com.bayair.doctor;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;

import com.bayair.doctor.biz.helper.SDKHelper;
import com.bayair.doctor.biz.helper.net_change.NetworkCallbackUtil;
import com.bayair.doctor.biz.im_helper.IMHelper;
import com.bayair.doctor.utils.log.KLog;
import com.hjq.bar.TitleBar;
import com.hjq.bar.style.TitleBarLightStyle;

public class App extends Application {

    private static Context sContext;

    public static Context getContext() {
        return sContext;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        sContext = this;

        SDKHelper.getInstance().init(this);

        unifiedConfig();

        initBackgroundCallBack();
    }

    private void unifiedConfig() {
        //TitleBar.initStyle(new QQTitleBarStyle(getApplicationContext()));
        TitleBar.initStyle(new TitleBarLightStyle(getApplicationContext()));

        NetworkCallbackUtil.register(this);
    }


    private void initBackgroundCallBack() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            }

            @Override
            public void onActivityStarted(Activity activity) {
                appCount++;
                if (isRunInBackground) {
                    //应用从后台回到前台 需要做的操作
                    back2App(activity);
                }
            }

            @Override
            public void onActivityResumed(Activity activity) {
            }

            @Override
            public void onActivityPaused(Activity activity) {
            }

            @Override
            public void onActivityStopped(Activity activity) {
                appCount--;
                if (appCount == 0) {
                    //应用进入后台 需要做的操作
                    leaveApp(activity);
                }
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
            }
        });

    }



    private int appCount;
    private boolean isRunInBackground;

    /**
     从后台回到前台需要执行的逻辑

     @param activity
     */
    private void back2App(Activity activity) {
        isRunInBackground = false;

        KLog.d("从后台回到前台需要执行的逻辑");
        //检查IM登录状况
        IMHelper.checkIMLogin();
    }

    /**
     离开应用 压入后台或者退出应用

     @param activity
     */
    private void leaveApp(Activity activity) {
        isRunInBackground = true;
        KLog.d("离开应用压入后台或者退出应用");
    }
}
